<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="preview"
      :class="{ disable:fileList.length > 0 }"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress v-if="showPercent" :percentage="percentage" style="width:148px" :show-text="false" />
    <!-- 做图片预览 -->
    <el-dialog title="预览" :visible="showDialog">
      <el-row type="flex" justify="center">
        <img :src="previewUrl" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
// 引入腾讯云开发工具并初始化实例
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDznKcdOs76oOo0xpTrxmKdeiV1GFxPbV8',
  SecretKey: 'NUKtAF3arrb4F9m8H9l7C0d2B3e05tPf'
})
export default {
  data() {
    return {
      fileList: [
        // {
        //   url: 'https://img.alicdn.com/imgextra/i3/6000000001226/O1CN01mTLirm1KvYGbpkCl2_!!6000000001226-2-octopus.png'
        // }
      ],
      showDialog: false,
      previewUrl: '',
      showPercent: false,
      percentage: 0
    }
  },
  methods: {
    //   点击已上传文件触发(这里参数存着已上传文件的url)
    preview(file) {
      console.log(file)
      this.previewUrl = file.url
      this.showDialog = true
    },
    // 点击删除
    onRemove(file, newFileList) {
      // console.log(file,newFileList)
    //   为了数组不被污染，要使用原来的数组
      this.fileList = [...newFileList]
    },
    // 替换成最新的文件
    onChange(file, newFileList) {
      this.fileList = [...newFileList]
    },
    // 覆盖默认上传
    upload(params) {
      console.log(params)
      // 进度条上传前
      this.showPercent = true
      cos.putObject({
        // 储存桶名
        Bucket: 'zcy63-1306481108',
        // 储存桶区域
        Region: 'ap-nanjing',
        // 要储存的文件名
        Key: Date.now() + params.file.name,
        // 储存类型,标准,固定不变
        StorageClass: 'STANDARD',
        // 文件对象本身
        Body: params.file,
        // 进度发生变化时回调
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // 上传完毕的回调不管成功失败都会到这
        console.log(err || data)
        // 没有错就是上传成功
        if (!err) {
          // 上传成功改成腾讯云的地址(上传成功返回值data中有)
          this.fileList[0].url = `http://${data.Location}`
          // 上传完成让右上角显示打勾
          this.fileList[0].status = 'success'
        }
        // 上传成功后进度条
        setTimeout(() => {
          this.showPercent = false
        }, 800)
      })
    },
    // 上传前校验
    beforeUpload(file) {
      console.log(file)
      // 1. 拦截格式
      const types = ['image/jpeg', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('目前只支持 jpeg / png 格式')
        return false
      }
      // 2. 拦截大小
      const maxSize = 900 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('只可上传小于 900 * 1024 * 1024 的图片')
        return false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep img {
  object-fit: contain;
}
.disable {
::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
